﻿using DevExpress.ExpressApp.Blazor.Components;
using DevExpress.ExpressApp.Blazor.Components.Models;
using DevExpress.ExpressApp.Blazor.Editors.Adapters;
using DevExpress.ExpressApp.Editors;
using DevExpress.ExpressApp.Utils;
using Microsoft.AspNetCore.Components;

namespace EasyXaf.Blazor.ColorPickers;

public class ColorPickerAdapter : ComponentAdapterBase
{
    public ColorPickerAdapter(ColorPickerModel model)
    {
        if (model is null)
        {
            throw new ArgumentNullException(nameof(model));
        }

        Model = model;
        Model.SetAttribute($"data-xaf-{ConditionalAppearanceModel.Id}", true);
        Model.ValueChanged = Model_ValueChanged;
        ValidationModel = new XafValidationMessageContainerModel();
    }

    public ColorPickerModel Model { get; }

    protected XafValidationMessageContainerModel ValidationModel { get; }

    private void Model_ValueChanged(object value)
    {
        Model.Value = value;
        RaiseValueChanged();
    }

    public override void SetAllowEdit(bool allowEdit)
    {
        Model.ReadOnly = !allowEdit;
    }

    public override void SetAllowNull(bool allowNull) { }

    public override void SetDisplayFormat(string displayFormat)
    {
        Model.DisplayFormat = displayFormat;
    }

    public override void SetEditMask(string editMask) { }

    public override void SetEditMaskType(EditMaskType editMaskType) { }

    public override void SetErrorIcon(ImageInfo errorIcon)
    {
        ValidationModel.ValidationResultType = GetValidationResultType(errorIcon);
        Model.CssClass = GetValidationCssClass(errorIcon);
    }

    public override void SetErrorMessage(string errorMessage)
    {
        ValidationModel.Message = errorMessage;
        Model.ErrorMessage = errorMessage;
    }

    public override void SetIsPassword(bool isPassword) => Model.Password = isPassword;

    public override void SetMaxLength(int maxLength) => Model.MaxLength = maxLength == 0 ? -1 : maxLength;

    public override void SetNullText(string nullText) => Model.NullText = nullText;

    public override object GetValue() => Model.Value;

    public override void SetValue(object value) => Model.Value = value;

    protected override RenderFragment CreateComponent() => ComponentModelObserver.Create(
        Model, ComponentModelObserver.Create(
            ConditionalAppearanceModel, ConditionalAppearanceContainer.Create(
                ConditionalAppearanceModel, GetConditionalAppearanceSelector(), XafValidationMessageContainer.Create(
                    ValidationModel, ColorPickerRenderer.Create(
                        Model)))));
}
